package me.wangcai.trafficpoliceai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.wangcai.trafficpoliceai.mapper.AppealMapper;
import me.wangcai.trafficpoliceai.mapper.UserMapper;
import me.wangcai.trafficpoliceai.mapper.ViolationMapper;
import me.wangcai.trafficpoliceai.model.ResponseInfo;
import me.wangcai.trafficpoliceai.model.entity.Appeal;
import me.wangcai.trafficpoliceai.model.entity.User;
import me.wangcai.trafficpoliceai.model.entity.Violation;
import me.wangcai.trafficpoliceai.service.IAppealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppealServiceImpl extends ServiceImpl<AppealMapper, Appeal> implements IAppealService {

    @Autowired
    private AppealMapper appealMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ViolationMapper violationMapper;

    @Override
    public ResponseInfo handle(int id, String username, boolean accept) {
        QueryWrapper<Appeal> query = Wrappers.query();
        query.eq("violation_id",id);
        Appeal appeal = appealMapper.selectOne(query);
        if(appeal == null) return ResponseInfo.error("没有这个申诉记录");
        if(appeal.getHandle_time() != null) return ResponseInfo.error("已处理过了!");
        appeal.setPass(accept);
        appeal.setViolationId(id);
        appeal.setHandle_time(LocalDate.now());
        appeal.setHandle_admin(username);
        appealMapper.updateById(appeal);
        Violation violation = violationMapper.selectOne(new QueryWrapper<Violation>().eq("id", id));
        violation.setHandle(true);
        violationMapper.updateById(violation);
        return ResponseInfo.success("处理成功");
    }

    @Override
    public ResponseInfo filterAppeal(HashMap<String, String> filterMap) {
        QueryWrapper<Appeal> wrapper = Wrappers.query();
        String searchCarId = filterMap.remove("carId");
        filterMap.forEach((k,v) -> {
            wrapper.like(k,v);
        });
        List<Map<String, Object>> list = appealMapper.selectMaps(wrapper);
        ArrayList<Map<String, Object>> newList = new ArrayList<>();
        for (Map<String, Object> stringObjectMap : list) {
            Integer violationId = Integer.parseInt(stringObjectMap.get("violation_id").toString());
            Violation violation = violationMapper.selectById(violationId);
            stringObjectMap.put("violation",violation);
            if(searchCarId != null && violation.getCarId().equals(searchCarId)){
                newList.add(stringObjectMap);
            }
        }

        return ResponseInfo.success("查询成功",newList);
    }
}
